import { getImageUrl } from '@/lib/utils';

export interface HomeData {
  id?: number;
  documentId?: string;
  home_title?: string;
  web?: string;
  description?: string;
  my_work?: string;
  work_description?: string;
  friend?: string;
  friend_description?: string;
  contact?: string;
  contact_description?: string;
  icp?: string;
  beian?: string;
  logo?: {
    url: string;
    width: number;
    height: number;
  };
  work_title?: string;
  friend_title?: string;
  contact_links?: {
    links: Array<{
      id?: number;
      documentId?: string;
      name: string;
      url: string;
      contact_icon?: {
        name: string;
        width: number;
        height: number;
        url: string;
      };
    }>;
  };
  createdAt?: string;
  updatedAt?: string;
  publishedAt?: string;
}

export interface AboutData {
  id: number;
  documentId: string;
  title: string;
  description: string;
  personal: string;
  skills: string;
  feature: string;
  education: string;
  language: string;
  createdAt: string;
  updatedAt: string;
  publishedAt: string;
}

export interface Friend {
  id: number;
  documentId: string;
  name: string;
  position: string;
  description: string;
  link: string;
  createdAt: string;
  updatedAt: string;
  publishedAt: string;
  Avatar: {
    id: number;
    documentId: string;
    name: string;
    width: number;
    height: number;
    url: string;
    formats?: {
      thumbnail?: {
        url: string;
        width: number;
        height: number;
      };
    };
  };
}

export interface FriendsResponse {
  data: Friend[];
  meta: {
    pagination: {
      page: number;
      pageSize: number;
      pageCount: number;
      total: number;
    };
  };
}

export interface ApiResponse<T> {
  data: T;
  meta: Record<string, unknown>;
}

const API_BASE_URL = process.env.NEXT_PUBLIC_BACKEND_URL;
const CACHE_TIME = 2 * 60 * 1000; // 调整为2分钟缓存

interface CacheItem<T> {
  data: T;
  timestamp: number;
}

const cache = new Map<string, CacheItem<any>>();

export async function fetchWithRetry(url: string, options: RequestInit = {}, retries = 5, backoff = 1000) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 15000); // 增加超时时间到15秒

  try {
    // 检查API_BASE_URL是否存在
    if (!API_BASE_URL) {
      throw new Error('API基础URL未配置，请检查环境变量NEXT_PUBLIC_BACKEND_URL');
    }

    // 添加重试前的日志，帮助调试
    if (retries < 5) {
      console.log(`尝试第${5-retries}次请求: ${url}`);
    }

    console.log('正在发起API请求:', {
      url: url,
      method: options.method || 'GET',
      headers: options.headers
    });

    // 使用try-catch包装fetch调用，以便更好地处理网络错误
    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal,
        // 使用传入的缓存选项，如果没有则使用默认的'force-cache'以支持静态生成
        cache: options.cache || 'force-cache',
        credentials: 'same-origin',
        keepalive: true
      });

      console.log('收到API响应:', {
        status: response.status,
        statusText: response.statusText,
        url: response.url
      });
      clearTimeout(timeoutId);

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(`API请求失败: ${response.status} - ${JSON.stringify(errorData)}`);
      }
      return response;
    } catch (fetchError) {
      // 专门处理fetch错误
      const fetchErr = fetchError instanceof Error ? fetchError : new Error(String(fetchError));
      
      // 处理网络连接错误
      if (fetchErr.name === 'TypeError' && fetchErr.message.includes('Failed to fetch')) {
        console.error(`网络连接失败 (可能是CORS问题或服务器不可达): ${url}`, fetchErr);
        throw fetchErr; // 让外层catch处理重试逻辑
      }
      
      throw fetchErr; // 其他fetch错误也抛出，让外层catch处理
    }
  } catch (error) {
    clearTimeout(timeoutId);
    // 确保error是一个对象，并且有name属性
    const err = error instanceof Error ? error : new Error(String(error));
    console.error('API请求错误详情:', {
      errorType: err.name,
      message: err.message,
      stack: err.stack
    });
    
    // 处理请求超时
    if (err.name === 'AbortError') {
      console.error(`请求超时: ${url}`);
      if (retries <= 0) {
        throw new Error(`请求超时: ${url}`);
      }
    }
    
    // 处理网络连接错误
    if (err.name === 'TypeError' && err.message.includes('Failed to fetch')) {
      console.error(`网络连接失败: ${url}`, err);
      if (retries <= 0) {
        throw new Error(`网络连接失败，请检查网络连接或服务器状态: ${url}`);
      }
    }
    
    // 如果没有重试次数了，抛出错误
    if (retries <= 0) {
      console.error(`请求失败且无重试次数: ${url}`, err);
      throw err;
    }
    
    // 计算重试延迟并进行重试
    const retryDelay = backoff * Math.pow(1.5, 5 - retries); // 调整退避算法
    console.warn(`请求失败，${retries}次重试剩余，${retryDelay}ms后重试:`, err.message);
    
    await new Promise(resolve => setTimeout(resolve, retryDelay));
    return fetchWithRetry(url, options, retries - 1, backoff);
  }
}

async function fetchWithCache<T>(url: string, options: RequestInit = {}): Promise<T> {
  const cacheKey = url;
  const cachedData = cache.get(cacheKey);

  if (cachedData && Date.now() - cachedData.timestamp < CACHE_TIME) {
    return cachedData.data;
  }

  try {
    const response = await fetchWithRetry(url, options);
    const jsonResponse = await response.json() as ApiResponse<T>;
    const data = jsonResponse.data;
    
    if (!data) {
      throw new Error(`API返回数据为空: ${url}`);
    }
    
    cache.set(cacheKey, { data, timestamp: Date.now() });
    return data;
  } catch (error) {
    console.error(`fetchWithCache 错误: ${url}`, error);
    // 清除无效缓存
    cache.delete(cacheKey);
    // 增强错误提示
    const err = error instanceof Error ? error : new Error(String(error));
    throw new Error(`获取数据失败: ${err.message} (URL: ${url})`);
  }
}

export const getHomeData = async (): Promise<HomeData> => {
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/home?populate=*`);
    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.message || 'Failed to fetch home data');
    }

    // 处理logo数据
    const homeData = data.data;
    let processedData: HomeData = {
      home_title: homeData.home_title,
      web: homeData.web,
      description: homeData.description,
      my_work: homeData.my_work,
      work_description: homeData.work_description,
      friend: homeData.friend,
      friend_description: homeData.friend_description,
      contact: homeData.contact,
      contact_description: homeData.contact_description,
      icp: homeData.icp,
      beian: homeData.beian,
      work_title: homeData.work_title,
      friend_title: homeData.friend_title,
      contact_links: homeData.contact_links,
    };

    // 如果API响应包含logo，添加到返回数据中
    if (homeData.logo) {
      processedData.logo = {
        url: getImageUrl(homeData.logo.url),
        width: homeData.logo.width,
        height: homeData.logo.height
      };
    }

    return processedData;
  } catch (error) {
    console.error('Error fetching home data:', error);
    throw error;
  }
};

export async function getFriends(): Promise<Friend[]> {
  try {
    // Use the direct URL instead of relying on API_BASE_URL
    const apiUrl = 'https://server.illli.cc/api/frineds?populate=*';
    
    const response = await fetch(apiUrl, {
      // Add additional options to avoid caching issues
      cache: 'no-store',
      next: { revalidate: 60 } // Revalidate every minute
    });
    
    if (!response.ok) {
      console.error(`API request failed with status: ${response.status}`);
      throw new Error(`API request failed: ${response.status}`);
    }
    
    // Log the raw response for debugging
    const responseText = await response.text();
    
    try {
      // Parse the JSON from the text
      const jsonData = JSON.parse(responseText) as FriendsResponse;
      
      if (!jsonData || !jsonData.data || !Array.isArray(jsonData.data)) {
        console.warn('Invalid friends data format:', jsonData);
        throw new Error('Invalid friends data format');
      }
      
      console.log('Successfully fetched friends data:', jsonData.data.length, 'friends');
      return jsonData.data;
    } catch (parseError) {
      console.error('Error parsing JSON response:', parseError);
      console.error('Raw response:', responseText);
      throw new Error('Failed to parse API response');
    }
  } catch (error) {
    console.error('获取朋友数据失败:', error);
    // Ensure error is an object with a message property
    const err = error instanceof Error ? error : new Error(String(error));
    
    // Provide more specific error messages
    let errorMessage = '获取朋友数据失败';
    if (err.message.includes('Failed to fetch') || err.message.includes('网络连接失败')) {
      errorMessage = '网络连接失败，请检查网络连接或服务器状态';
    } else if (err.message.includes('Invalid friends data format')) {
      errorMessage = '朋友数据格式无效';
    } else if (err.message.includes('Failed to parse API response')) {
      errorMessage = 'API响应解析失败';
    } else if (err.message.includes('请求超时')) {
      errorMessage = '服务器响应超时，请稍后重试';
    }
    
    throw new Error(errorMessage);
  }
}

export interface BlogPost {
  id: number;
  documentId: string;
  title: string;
  content: string;
  category: string;
  createdAt: string;
  updatedAt: string;
  publishedAt: string;
}

export async function getAboutData(): Promise<AboutData> {
  try {
    // 检查API_BASE_URL是否存在
    if (!API_BASE_URL) {
      throw new Error('API基础URL未配置，请检查环境变量NEXT_PUBLIC_BACKEND_URL');
    }
    
    const response = await fetchWithRetry(`${API_BASE_URL}/api/about?populate=*`);
    const jsonResponse = await response.json();
    
    // 确保返回的数据符合AboutData结构
    if (!jsonResponse || !jsonResponse.data) {
      console.warn('API返回的关于页数据格式不符合预期:', jsonResponse);
      throw new Error('无效的关于页数据格式');
    }
    
    return jsonResponse.data;
  } catch (error) {
    console.error('获取关于页数据失败:', error);
    // 确保error是一个对象，并且有message属性
    const err = error instanceof Error ? error : new Error(String(error));
    
    // 提供更具体的错误信息
    let errorMessage = '获取关于页数据失败';
    if (err.message.includes('Failed to fetch') || err.message.includes('网络连接失败')) {
      errorMessage = '网络连接失败，请检查网络连接或服务器状态';
    } else if (err.message.includes('API基础URL未配置')) {
      errorMessage = '系统配置错误，请联系管理员';
    } else if (err.message.includes('请求超时')) {
      errorMessage = '服务器响应超时，请稍后重试';
    }
    
    throw new Error(errorMessage);
  }
}

export interface Project {
  id: number;
  documentId: string;
  title: string;
  year: string;
  who: string;
  results: { title: string }[];
  link: string;
  image?: {
    url: string;
    width: number;
    height: number;
  };
  createdAt: string;
  updatedAt: string;
  publishedAt: string;
}

export interface ProjectsResponse {
  data: Project[];
  meta: {
    pagination: {
      page: number;
      pageSize: number;
      pageCount: number;
      total: number;
    };
  };
}

export async function getProjects(): Promise<Project[]> {
  const cacheKey = 'projects';
  const cachedData = cache.get(cacheKey);

  if (cachedData && Date.now() - cachedData.timestamp < CACHE_TIME) {
    return cachedData.data;
  }

  try {
    // 检查API_BASE_URL是否存在
    if (!API_BASE_URL) {
      throw new Error('API基础URL未配置，请检查环境变量NEXT_PUBLIC_BACKEND_URL');
    }
    
    const response = await fetchWithRetry(
      `${API_BASE_URL}/api/works?populate=*`,
      { cache: 'force-cache' }
    );

    const jsonResponse = await response.json() as ProjectsResponse;
    const projects = jsonResponse.data;
    cache.set(cacheKey, { data: projects, timestamp: Date.now() });
    return projects;
  } catch (error) {
    console.error('获取项目数据失败:', error);
    // 确保error是一个对象，并且有message属性
    const err = error instanceof Error ? error : new Error(String(error));
    
    // 提供更具体的错误信息
    let errorMessage = '获取项目数据失败';
    if (err.message.includes('Failed to fetch') || err.message.includes('网络连接失败')) {
      errorMessage = '网络连接失败，请检查网络连接或服务器状态';
    } else if (err.message.includes('API基础URL未配置')) {
      errorMessage = '系统配置错误，请联系管理员';
    } else if (err.message.includes('请求超时')) {
      errorMessage = '服务器响应超时，请稍后重试';
    }
    
    // 在开发环境中抛出错误，在生产环境中返回空数组
    if (process.env.NODE_ENV === 'development') {
      throw new Error(errorMessage);
    }
    return [];
  }
}

export interface BlogPost {
  id: number;
  documentId: string;
  slug: string;
  title: string;
  description: string;
  data: string;
  category: string;
  content: string;
  createdAt: string;
  updatedAt: string;
  publishedAt: string;
  bg_image?: {
    id: number;
    documentId: string;
    name: string;
    alternativeText: string | null;
    caption: string | null;
    width: number;
    height: number;
    formats: {
      small?: {
        ext: string;
        url: string;
        hash: string;
        mime: string;
        name: string;
        path: string | null;
        size: number;
        width: number;
        height: number;
        sizeInBytes: number;
      };
      medium?: {
        ext: string;
        url: string;
        hash: string;
        mime: string;
        name: string;
        path: string | null;
        size: number;
        width: number;
        height: number;
        sizeInBytes: number;
      };
      thumbnail?: {
        ext: string;
        url: string;
        hash: string;
        mime: string;
        name: string;
        path: string | null;
        size: number;
        width: number;
        height: number;
        sizeInBytes: number;
      };
    };
    hash: string;
    ext: string;
    mime: string;
    size: number;
    url: string;
    previewUrl: string | null;
    provider: string;
    provider_metadata: any | null;
    createdAt: string;
    updatedAt: string;
    publishedAt: string;
  };
}

export interface BlogResponse {
  data: BlogPost[];
  meta: {
    pagination: {
      page: number;
      pageSize: number;
      pageCount: number;
      total: number;
    };
  };
}

export async function getBlogPosts(page = 1, pageSize = 10): Promise<BlogResponse> {
  const cacheKey = `blog_posts_${page}_${pageSize}`;
  const cachedData = cache.get(cacheKey);

  if (cachedData && Date.now() - cachedData.timestamp < CACHE_TIME) {
    return cachedData.data;
  }

  try {
    // 检查API_BASE_URL是否存在
    if (!API_BASE_URL) {
      throw new Error('API基础URL未配置，请检查环境变量NEXT_PUBLIC_BACKEND_URL');
    }
    
    const response = await fetchWithRetry(
      `${API_BASE_URL}/api/blogs?populate=*&pagination[page]=${page}&pagination[pageSize]=${pageSize}`,
      { 
        cache: 'force-cache',
        next: { revalidate: 3600 } // 每小时重新验证一次
      }
    );

    const jsonResponse = await response.json() as BlogResponse;
    
    // 确保返回的数据符合预期结构
    if (!jsonResponse || !jsonResponse.data) {
      console.warn('API返回的博客数据格式不符合预期:', jsonResponse);
      throw new Error('无效的博客数据格式');
    }
    
    cache.set(cacheKey, { data: jsonResponse, timestamp: Date.now() });
    return jsonResponse;
  } catch (error) {
    console.error('获取博客文章失败:', error);
    // 确保error是一个对象，并且有message属性
    const err = error instanceof Error ? error : new Error(String(error));
    
    // 提供更具体的错误信息
    let errorMessage = '获取博客文章失败';
    if (err.message.includes('Failed to fetch') || err.message.includes('网络连接失败')) {
      errorMessage = '网络连接失败，请检查网络连接或服务器状态';
    } else if (err.message.includes('API基础URL未配置')) {
      errorMessage = '系统配置错误，请联系管理员';
    } else if (err.message.includes('请求超时')) {
      errorMessage = '服务器响应超时，请稍后重试';
    }
    
    // 在开发环境中抛出错误，在生产环境中返回空数据
    if (process.env.NODE_ENV === 'development') {
      throw new Error(errorMessage);
    }
    
    return {
      data: [],
      meta: {
        pagination: {
          page: page,
          pageSize: pageSize,
          pageCount: 0,
          total: 0
        }
      }
    };
  }
}

export async function getBlogPost(slug: string): Promise<BlogPost | null> {
  const cacheKey = `blog_post_${slug}`;
  const cachedData = cache.get(cacheKey);

  if (cachedData && Date.now() - cachedData.timestamp < CACHE_TIME) {
    return cachedData.data;
  }

  try {
    // 检查API_BASE_URL是否存在
    if (!API_BASE_URL) {
      throw new Error('API基础URL未配置，请检查环境变量NEXT_PUBLIC_BACKEND_URL');
    }
    
    const response = await fetchWithRetry(
      `${API_BASE_URL}/api/blogs?filters[slug][$eq]=${slug}&populate=*`,
      { 
        cache: 'force-cache',
        next: { revalidate: 3600 } // 每小时重新验证一次
      }
    );

    const jsonResponse = await response.json() as BlogResponse;

    if (!jsonResponse.data || jsonResponse.data.length === 0) {
      return null;
    }

    const blogPost = jsonResponse.data[0];
    cache.set(cacheKey, { data: blogPost, timestamp: Date.now() });
    return blogPost;
  } catch (error) {
    console.error(`获取博客文章 ${slug} 失败:`, error);
    // 确保error是一个对象，并且有message属性
    const err = error instanceof Error ? error : new Error(String(error));
    
    // 提供更具体的错误信息
    let errorMessage = `获取博客文章 ${slug} 失败`;
    if (err.message.includes('Failed to fetch') || err.message.includes('网络连接失败')) {
      errorMessage = '网络连接失败，请检查网络连接或服务器状态';
    } else if (err.message.includes('API基础URL未配置')) {
      errorMessage = '系统配置错误，请联系管理员';
    } else if (err.message.includes('请求超时')) {
      errorMessage = '服务器响应超时，请稍后重试';
    }
    
    // 在开发环境中抛出错误，在生产环境中返回null
    if (process.env.NODE_ENV === 'development') {
      throw new Error(errorMessage);
    }
    
    return null;
  }
}

export async function getAllBlogSlugs(): Promise<string[]> {
  const cacheKey = 'all_blog_slugs';
  const cachedData = cache.get(cacheKey);

  if (cachedData && Date.now() - cachedData.timestamp < CACHE_TIME) {
    return cachedData.data;
  }

  try {
    // 检查API_BASE_URL是否存在
    if (!API_BASE_URL) {
      throw new Error('API基础URL未配置，请检查环境变量NEXT_PUBLIC_BACKEND_URL');
    }
    
    const response = await fetchWithRetry(
      `${API_BASE_URL}/api/blogs?fields[0]=slug&pagination[pageSize]=100`,
      { 
        cache: 'force-cache',
        next: { revalidate: 3600 } // 每小时重新验证一次
      }
    );

    const jsonResponse = await response.json() as BlogResponse;
    
    // 确保返回的数据符合预期结构
    if (!jsonResponse || !jsonResponse.data) {
      console.warn('API返回的博客slug数据格式不符合预期:', jsonResponse);
      throw new Error('无效的博客slug数据格式');
    }
    
    const slugs = jsonResponse.data.map((post: BlogPost) => post.slug);
    
    cache.set(cacheKey, { data: slugs, timestamp: Date.now() });
    return slugs;
  } catch (error) {
    console.error('获取所有博客文章slug失败:', error);
    // 确保error是一个对象，并且有message属性
    const err = error instanceof Error ? error : new Error(String(error));
    
    // 提供更具体的错误信息
    let errorMessage = '获取博客文章列表失败';
    if (err.message.includes('Failed to fetch') || err.message.includes('网络连接失败')) {
      errorMessage = '网络连接失败，请检查网络连接或服务器状态';
    } else if (err.message.includes('API基础URL未配置')) {
      errorMessage = '系统配置错误，请联系管理员';
    } else if (err.message.includes('请求超时')) {
      errorMessage = '服务器响应超时，请稍后重试';
    }
    
    // 在开发环境中抛出错误，在生产环境中返回空数组
    if (process.env.NODE_ENV === 'development') {
      throw new Error(errorMessage);
    }
    
    return [];
  }
}

export interface NavigationItem {
  id: number;
  documentId: string;
  title: string;
  description: string;
  link: string;
  createdAt: string;
  updatedAt: string;
  publishedAt: string;
  image?: {
    id: number;
    documentId: string;
    name: string;
    alternativeText: string | null;
    caption: string | null;
    width: number;
    height: number;
    formats: any;
    hash: string;
    ext: string;
    mime: string;
    size: number;
    url: string;
    previewUrl: string | null;
    provider: string;
    provider_metadata: any;
    createdAt: string;
    updatedAt: string;
    publishedAt: string;
  };
}

export interface NavigationResponse {
  data: NavigationItem[];
  meta: {
    pagination: {
      page: number;
      pageSize: number;
      pageCount: number;
      total: number;
    };
  };
}

export async function getNavigations(): Promise<NavigationItem[]> {
  const cacheKey = 'navigations';
  const cachedData = cache.get(cacheKey);

  if (cachedData && Date.now() - cachedData.timestamp < CACHE_TIME) {
    return cachedData.data;
  }

  try {
    // 检查API_BASE_URL是否存在
    if (!API_BASE_URL) {
      throw new Error('API基础URL未配置，请检查环境变量NEXT_PUBLIC_BACKEND_URL');
    }
    
    const response = await fetchWithRetry(
      `${API_BASE_URL}/api/navigations?populate=*`,
      { 
        cache: 'force-cache',
        next: { revalidate: 3600 } // 每小时重新验证一次
      }
    );

    const jsonResponse = await response.json() as NavigationResponse;
    
    // 确保返回的数据符合预期结构
    if (!jsonResponse || !jsonResponse.data) {
      console.warn('API返回的导航数据格式不符合预期:', jsonResponse);
      throw new Error('无效的导航数据格式');
    }
    
    cache.set(cacheKey, { data: jsonResponse.data, timestamp: Date.now() });
    return jsonResponse.data;
  } catch (error) {
    console.error('获取导航数据失败:', error);
    // 确保error是一个对象，并且有message属性
    const err = error instanceof Error ? error : new Error(String(error));
    
    // 提供更具体的错误信息
    let errorMessage = '获取导航数据失败';
    if (err.message.includes('Failed to fetch') || err.message.includes('网络连接失败')) {
      errorMessage = '网络连接失败，请检查网络连接或服务器状态';
    } else if (err.message.includes('API基础URL未配置')) {
      errorMessage = '系统配置错误，请联系管理员';
    } else if (err.message.includes('请求超时')) {
      errorMessage = '服务器响应超时，请稍后重试';
    }
    
    // 在开发环境中抛出错误，在生产环境中返回空数组
    if (process.env.NODE_ENV === 'development') {
      throw new Error(errorMessage);
    }
    return [];
  }
}
